<?php
// +----------------------------------------------------------------------
// | 评论模块
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: CommentAction.class.php 123 2011-05-18 09:46:17Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class CommentAction extends BaseAction {
	
	// 改自wp-recentcomments插件
	public function recentComment() {
	
		if ($_REQUEST['act'] == 'recent_ajax') {
		
			$start = $_GET['start'];
			
			$loading_text = 'Loading';
			
			if ($start < 0) {
				$start = 0;
			}
			
			/* 最新评论列表数量 */
			$limit = C('recent_comments_num');
			
			/* 准备多取一个, 以便获知是否有更多评论存在 */
			$size = $limit + 1;
			
			/* 查询过滤 */
			$map  =	 array();		
			$map[C('DB_PREFIX').'comment.comment_status'] = 1; 
			$map[C('DB_PREFIX').'comment.comment_visible'] = 1;
			$map[C('DB_PREFIX').'comment.comment_type'] = array('neq',2);
			$map[C('DB_PREFIX').'posts.posts_status'] = 1;
			if (C('remark')) {
				$map[C('DB_PREFIX').'comment.comment_remark'] = 1;
			}
			
			$com  =  M('Comment');	
			$comments = $com->where($map)->field(C('DB_PREFIX').'posts.posts_title,'.C('DB_PREFIX').'posts.posts_url,'.C('DB_PREFIX').'comment.*')->join(C('DB_PREFIX').'posts ON '.C('DB_PREFIX').'posts.posts_id = '.C('DB_PREFIX').'comment.posts_id')->order('comment_id desc')->limit($start.','.$size)->findAll();
			
			/* 如果能够获取多一个元组, 证明有更多评论存在, 需要显示 Older 按钮 */
			$has_older = (count($comments) - $limit > 0);
			
			/* 有更多评论存在时, 删除最后那个多余的 */
			if ($has_older) {
				array_pop($comments);
			}
			 
			/* 获取最新评论列表 */
			$result = ''; $count = 0;
			if ($comments) {
				foreach ($comments as $v) {
		
					/* 用户头像 */
					$element_avatar = get_gravatar($v['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
		
					/* 获取摘要 */
					$comment_excerpt = preg_replace('/(\r\n)|(\n)/', '', $v['comment_content']); // 消灭换行符
					$comment_excerpt = rc_remove_blockquotes($comment_excerpt); // 消灭所有 blockquote 内容
					$comment_excerpt = preg_replace('/\<(.+?)\>/', '', $comment_excerpt); // 消灭所有标签
					$comment_excerpt = msubstr($comment_excerpt, 0, C('recent_comments_limit'));
					$comment_excerpt = rc_substring($comment_excerpt, $v['comment_id'], $start);
		
					/* 处理摘要里的表情 */
					if ((strlen($comment_excerpt) > 0)) {
						$comment_excerpt = convert_smilies($comment_excerpt);
					}
		
					/* 获取信息 */		
					/*$result .= '<li id="rc_item_'.++$count.'" class="rc_item">';
					$result .= '<div class="rc_avatar rc_left"><img src="'.$element_avatar.'" class="avatar avatar-32 photo" width="32" height="32"></div>';
					$result .= '<div class="rc_info"><span class="author_name"><a href="'.C('blog_domain').'posts/'.$v['posts_url'].'#comment-'.$v['comment_id'].'" title="['.$v['comment_author'].'] 发表在 ['.$v['posts_title'].']">'.$v['comment_author'].'</a></span></div>';
					$result .= '<div class="rc_content"><span id="comment-'.$v['comment_id'].'_" style="display: block; float:left;" >'.$comment_excerpt.'...</span><span><a href="javascript:showComments(\'comment-'.$v['comment_id'].'\');"><b id="comment-'.$v['comment_id'].'__">&nbsp;&raquo;</b></a></span></div>';
					$result .= '<div style="display: none;" class="rc_content" id="comment-'.$v['comment_id'].'">';
					$result .= '<p>'.$v['comment_content'].'</p></div></li>';*/
					
					$result .= '<li id="rc_item_'.++$count.'" class="rc_item">';
					$result .= '<div class="rc_avatar rc_left"><img src="'.$element_avatar.'" class="avatar avatar-32 photo" width="32" height="32" /></div>';
					$result .= '<div class="rc_info"><span class="author_name"><a rel="nofollow" href="'.__APP__.'/Posts/'.$v['posts_url'].'#comment-'.$v['comment_id'].'" title="'.$v['posts_title'].'">'.$v['comment_author'].'</a></span></div>';
					$result .= $comment_excerpt.'</li>';
				}

				/* 新评论和老评论的开始位置 */
				$newer_start = $start - $limit;
				$older_start = $start + $limit;
		
				/* Newest 按钮 */
				$newest = '';
				// 判断是否还有最新评论
				// 第一页不需要显示最新评论的链接
				// 第二页功能与 Newer 链接功能相同, 也不需显示
				// 第三页开始才有必要显示出来
				$has_newest = ($start >= $limit * 2);
				if ($has_newest) {
					$newest = '<div id="rc_newest"><a rel="nofollow" href="javascript:void(0);" onclick="RCJS.page(\''.__APP__.'/Comment/recentComment\',\'0\',\'' . $loading_text . '\');">&laquo; Newest</a></div>';
				}
		
				/* Newer 按钮 */
				$newer = '';
				// 判断是否还有新评论
				// 只要前面还有新的评论, 就要显示.
				$has_newer = ($start > 0);
				if ($has_newer) {
					// 如果开始位置为负数, 将它修改为 0
					if ($newer_start < 0) {
						$newer_start = 0;
					}
					$newer = '<div id="rc_newer"><a rel="nofollow" href="javascript:void(0);" onclick="RCJS.page(\''.__APP__.'/Comment/recentComment\',' . $newer_start . ',\'' . $loading_text . '\');">&laquo; Newer</a></div>';
				}
		
				/* Older 按钮 */
				$older = '';
				if ($has_older) {
					$older = '<div id="rc_older"><a rel="nofollow" href="javascript:void(0);" onclick="RCJS.page(\''.__APP__.'/Comment/recentComment\',' . $older_start . ',\'' . $loading_text . '\');">Older &raquo;</a></div>';
				}
		
				/* 当需要显示 Newer 或 Older 按钮时才显示这一栏 */
				if ($has_newer || $has_older) {
					$result .= '<li class="rc_navi rc_clearfix">' . $newest . $newer . $older . '</li>';
				}
		
				/* 返回 HTML 格式的字符串 */
				echo $result;
			}
			
		} else {
			$this->error('非法操作');
		}
	}
	
	public function detailComment() {
	
		if ($_REQUEST['act'] == 'detail_ajax') {
		
			$id = $_GET['id'];
			$start = $_GET['start'];
			$loading_text = 'Loading';
			
			/* 查询过滤 */
			$map  =	 array();
			$map[C('DB_PREFIX').'comment.comment_id'] = $id; 		
			$map[C('DB_PREFIX').'comment.comment_status'] = 1; 
			$map[C('DB_PREFIX').'comment.comment_visible'] = 1;
			$map[C('DB_PREFIX').'comment.comment_type'] = array('neq',2);
			$map[C('DB_PREFIX').'posts.posts_status'] = 1;
			if (C('remark')) {
				$map[C('DB_PREFIX').'comment.comment_remark'] = 1;
			}
			
			$com  =  M('Comment');	
			$comments = $com->where($map)->field(C('DB_PREFIX').'posts.posts_title,'.C('DB_PREFIX').'posts.posts_url,'.C('DB_PREFIX').'comment.*')->join(C('DB_PREFIX').'posts ON '.C('DB_PREFIX').'posts.posts_id = '.C('DB_PREFIX').'comment.posts_id')->find();
			
			/* 用户头像 */
			$element_avatar = get_gravatar($comments['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
			
			/* 处理 blockquote */
			$content = rc_remove_blockquotes_but_outermost($comments['comment_content']);
			
			/* 处理摘要里的表情 */
			if ((strlen($content) > 0)) {
				$content = convert_smilies($content);
			}
			
			/* 处理抛锚链接 */
			$content = preg_replace(array('/href="#/', '/href=\'#/'), array('href="'.__APP__.'/Posts/'.$comments['posts_url'].'#', 'href=\''.__APP__.'/Posts/'.$comments['posts_url'].'#'), $content);
	
			/* 日期时间 */
			$datetime = date('G:i',  $comments['comment_addtime']).' on '.date('F d, Y',  $comments['comment_addtime']);
			
			// 组合 HTML 格式的字符串
			$result  = '<li id="rc_item_1" class="rc_item">';
			$result .= '<div class="rc_avatar rc_left"><img src="'.$element_avatar.'" class="avatar avatar-32 photo" width="32" height="32"></div>';
			$result .= '<div class="rc_info"><span class="author_name"><a href="'.__APP__.'/Posts/'.$comments['posts_url'].'#comment-'.$comments['comment_id'].'" title="'.$comments['posts_title'].'">'.$comments['comment_author'].'</a></span></div>';
			$result .= '<div class="rc_fixed"></div></li>';
			$result .= '<li id="rc_item_2" class="rc_item"><div class="rc_content"><p>' . $content . '</p></div></li>';
			$result .= '<li class="rc_navi rc_clearfix">';
			$result .= '<a class="rc_back" href="javascript:void(0);" onclick="RCJS.page(\'' . __APP__ . '/Comment/recentComment\',' . $start . ',\'' . $loading_text . '\');">&laquo; Back</a>';
			$result .= '<span class="rc_datetime">' . $datetime. '</span>';
			$result .= '</li>';
	
			echo wpautop($result);	
			
		} else {
			$this->error('非法操作');
		}
	}
	
	public function post() {
	
	    //验证码
	    if (C('verify')) {
			if($_SESSION['verify'] != md5($_POST['verify'])) {
				$this->error('错误：验证码错误，请重新输入。');
			}
		}
		
		//禁止IP	
		if (C('filter_ip')) {
			$ban_ip = split_ip(trim(C('filter_ip')));
			if (is_array($ban_ip) && count($ban_ip)) {
				foreach ($ban_ip as $val) {
					$val = str_replace( '\*', '.*', preg_quote($val, "/") );
					if (preg_match("/^$val/", get_client_ip())) {
						$this->error('错误：您的IP已经被系统禁止发表留言/评论。');
					}
				}
			}
		}
		
		//留言时间间隔
		if (C('space')) {
			$lastposttime = Cookie::get('post_time');
			if (C('space') && time() - $lastposttime <= C('space')){
				$this->error('错误：您两次发表间隔应该大于'.C('space').'秒。');
			}
		}
		
		$gb  =  D ('Comment');
		$cookietime = 3600*24;
		
		if($gb->create()) {
		
			$gb->comment_author  = trim(strip_tags($gb->comment_author));
			$gb->comment_email   = trim($gb->comment_email);
			$gb->comment_url     = $gb->comment_url ? trim($gb->comment_url) : NULL;
			$gb->comment_ip      = get_client_ip();
			$gb->comment_content = preg_replace('/<(\/?)(script|i?frame|style|html|body|title|link|meta|img|\?|\%)([^>]*?)>/isU', '', $gb->comment_content);
			
			//过滤用户名
			$res = filter_name($gb->comment_author);
			switch($res) {
				case '0' : $this->error('错误：用户名太长。');
				case '-1' : $this->error('错误：此用户名包含不可接受字符，请选择其它用户名。');
				case '-2' : $this->error('错误：此用户名被管理员屏蔽，请选择其它用户名。');
			}
			
			//链接次数
			if (C('spam_url_num')) {
				if (substr_count($gb->comment_content, 'http://') >= C('spam_url_num')) {
					$spam = true;
				}
			}
		
			//过滤内容
			if (C('filter_words')) {
				$ban_words = explode('|',trim(C('filter_words')));	
				if (is_array($ban_words) && count($ban_words) ) {
					foreach ($ban_words as $val) {
						if ($val) {
							if (preg_match( "/".preg_quote($val, '/' )."/i", $gb->comment_content)) {
								$spam = true;
								break;
							}
						}
					}
				}
			}
			
			//表情处理
			
				
			//内容长度
			if (strlen($gb->comment_content) >= C('comment_maxlength')) {
				$this->error('错误：您的留言内容长度不符合要求，最多'.C('comment_maxlength').'个字节数。');
			} 
			else if (strlen($gb->comment_content) < C('comment_minlength')) {
				$this->error('错误：您的留言内容长度不符合要求，最少'.C('comment_minlength').'个字节数。');
			}
			
			$gb->comment_visible = $spam ? '0' : '1';
			
			$map  =	 array();
			$map['comment_author']  = $gb->comment_author;
			$map['comment_content'] = $gb->comment_content;
			$list = $gb->where($map)->find();
			if ($list['comment_id']) {
				$this->error('错误：重复发表留言，您好像发表过类似的留言。');
			}
			if ($vo = $gb->add()) {
				Cookie::set('comment_author_'. C('COOKIEHASH'), $gb->comment_author, $cookietime, C('COOKIEPATH'));
				Cookie::set('comment_email_'. C('COOKIEHASH'), $gb->comment_email, $cookietime, C('COOKIEPATH'));
				Cookie::set('comment_url_'. C('COOKIEHASH'), $gb->comment_url, $cookietime, C('COOKIEPATH'));
				Cookie::set('post_time',time());
				if ($spam) {
					$this->ajaxReturn('','此留言需要管理员审核后才能显示',0);
				}
				//发送邮件处理
				$output = $this->getName($gb->comment_content);
				if ($output) {
					$emails = $this->getEmail($_POST['comment_type']);
					foreach ($output as $name) {
						if (array_key_exists($name,$emails)) {
							$to = $emails["$name"];
							$this->sendEmail($vo, $name, $to, $gb->comment_author);
						}
					}
				}
				//处理热度
				$com_id = $this->getId($gb->comment_content);
				$pk   =  $gb->getPk();
				$condition = array ($pk => array ('in', $com_id));
				$gb->where($condition)->setInc('comment_replaynum');
				
				$gb->comment_addtime = date('F jS, Y', $gb->comment_addtime).' at '.date('G:i', $gb->comment_addtime);
				
				//构造新留言html
				$html  = '<li class="comment" id="comment-'.$vo.'"><div id="comment-'.$vo.'-"><div class="userinfo">';
				$html .= '<div class="userpic"><img src="'.get_gravatar($gb->comment_email).'" class="avatar avatar-24 photo" width="24" height="24"></div>';
				$html .= '<div class="usertext"><div class="username">';
				if ($gb->comment_url) {
					$html .= '<a id="reviewer-'.$vo.'" href="'.$gb->comment_url.'" rel="external nofollow">'.$gb->comment_author.'</a>';
				} else {
					$html .= '<span id="reviewer-'.$vo.'">'.$gb->comment_author.'</span>';
				}
				$html .= ' <a class="anchor" rel="nofollow" href="#comment-'.$vo.'">#'.$vo.'</a></div>';
				$html .= '<div class="date">'.$gb->comment_addtime.'</div></div><div class="fixed"></div></div><div class="comment_text">';
				$html .= '<div id="commentbody-'.$vo.'"><p>'.convert_smilies($gb->comment_content).'</p></div></div></div></li>';
				
				$this->ajaxReturn($html,'',1);
				
            } else {
                $this->error('Oops, failed to post data.');
            }
		}else{
			$this->error($gb->getError());
		}
	}
	
	public function detail() {
	
		if ($_REQUEST['act'] == 'detail_ajax') {
		
			$id = $_GET['id'];
			
			/* 查询过滤 */
			$map  =	 array();
			$map['comment_id'] = $id;	
			
			$gb = M('Comment');
			$vo	= $gb->where($map)->find();
			
			/* 用户头像 */
			$element_avatar = get_gravatar($vo['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
			
			/* 日期 */
			$datetime = date('F jS, Y', $vo['comment_addtime']).' at '.date('G:i', $vo['comment_addtime']);
			
			$result  = '<div class="userinfo">';
			$result .= '<div class="userpic"><img src="'.$element_avatar.'" class="avatar avatar-24 photo" width="24" height="24"></div>';
			$result .= '<div class="usertext"><div class="username">';
			if ($vo['comment_url']) {
				$result .= '<a id="reviewer-'.$vo['comment_id'].'" href="'.$vo['comment_url'].'" rel="external nofollow">'.$vo['comment_author'].'</a>';
			} else {
				$result .= '<span id="reviewer-'.$vo['comment_id'].'">'.$vo['comment_author'].'</span>';
			}
			$result .= ' <a class="anchor" rel="nofollow" href="#comment-'.$vo['comment_id'].'">#'.$vo['comment_id'].'</a></div><div class="date">'.$datetime.'</div></div>';
			$result .= '<div class="count"></div>';
			$result .= '<div class="fixed"></div></div>';
			$result .= '<div class="comment_text"><div id="commentbody-'.$vo['comment_id'].'">';
			$result .= '<p>'.$vo['comment_content'].'</p></div></div>';
			
			echo $result;
			
		} else {
			$this->error('非法操作');
		}
	}
	
	
	//获取用户留言内容中回复的人的昵称
	protected function getName($content) {
	
		$content = preg_replace('/<a\shref="#comment-[0-9]+">/s','',$content);
		$content = preg_replace('/<a\shref="#comment-([0-9])+"\srel="nofollow">/s','',$content);
		$content = preg_replace('/<a\srel="nofollow"\shref="#comment-([0-9])+">/s','',$content);
		$names   = explode(' ',$content);

		$output = array();
		foreach($names as $val){
			$number = substr_count($val,'@');
			if ($number >0 ){
				$length = strlen($val);
				$pos = strrpos($val,'@')+1;
				$n = substr($val,$pos,$length);
				$output["$n"] = $n;
			}
		}
		return $output;
	}
	
	//获取用户邮件
	protected function getEmail($int){
		$gb  =  M ('Comment');
		$map['comment_visible'] = 1;
		$map['comment_type'] = $int; 
		$map['comment_notify'] = 1;
		$list = $gb->where($map)->order('comment_id desc')->findAll();
		$temp =array();
		foreach ($list as $val){
			$name = $val['comment_author'];
			if(!array_key_exists($name,$temp)){
				$email = $val['comment_email'];
				$temp["$name"] = $email;
			}
		}
		return $temp;
	}
	
	//发送邮件
	protected function sendEmail($id, $name, $to, $comment_author) {
	
		$body = $name.'，您好：<br/>您在 '.C('blog_name').' 上的留言被（'.$comment_author.'）回复了，快去看看吧^_^<br/>';
		$body .= '<div style="margin-top:10px;margin-left:10px;padding-bottom:10px;border-bottom:1px solid #ccc;">';
		$body .= '<a href=\''.C('blog_domain').'Guestbook#comment-'.$id.'\' target=\'_blank\'>查看回复</a></div>';
		$body .= '<p>感谢您对 <a href="'.C('blog_domain').'">'.C('blog_name').'</a> 的关注</p>';
		$body .= '<p><strong>This email was sent automatically. Please don\'t reply to this email.</strong></p>';
		
		import('@.ORG.Phpmailer');				
		$mail = new PHPMailer();   
		$mail->IsSMTP();
		$mail->Username = C('smtp_user'); 
		$mail->Password = C('smtp_pass');
		$mail->From     = C('smtp_mail');   
		$mail->Host     = C('smtp_host');
		$mail->Port     = C('smtp_port');
		$mail->Mailer   = "smtp";   
		$mail->FromName = C('blog_name'); 
		$mail->IsHTML(true); 
		$mail->SMTPAuth = true;
		$mail->CharSet  = "utf-8";
		$mail->Encoding = "base64";  
		$mail->Subject  = '您在 '.C('blog_name').' 上的留言刚刚被 '.$comment_author.' 回复了'; 
		$mail->AddAddress("$to", "");
		$mail->Body     = $body;
		@$mail->Send();
		// Clear all addresses and attachments for next loop   
		$mail->ClearAddresses();   
		$mail->ClearAttachments();
	}
	
	//他妈不会正则,怎么办
	protected function getId($content) {
		$reg = '/\shref="#comment-([0-9]+)/s';
		preg_match_all($reg , $content , $out_ary);
		return $out_ary[1];
	}

}

?>